package com.aptech.action;


import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.aptech.dao.LoginDao;
import com.aptech.model.Userprofile;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class Login extends ActionSupport {

	private Userprofile user;
	
	//判断登录界面是否合法
	@Override
	public void validate() {
		if(user.getUsername().equals(""))
		{
			this.addFieldError("LoginError","用户名不予许为空！" );
		}
		if(user.getPassword().equals("")){
			this.addFieldError("LoginError","密码不允许为空！" );
		}
		if(user.getUsername().length()>10){
			this.addFieldError("LoginError","请输入小与11位的用户名！" );
		}
		if(user.getPassword().length()>15){
			this.addFieldError("LoginError","请输入正确密码，密码长度为1—15位" );
		}
	}

	public String selectUserLoginByUserName(){
		HttpServletRequest request=ServletActionContext.getRequest();
		
		//调用LoginDao层的登录方法验证登录
		LoginDao logindao=new LoginDao();
		String st=logindao.userLogin(user);
		if(st.equals("notUser")){
			String s="用户不存在！";
			request.setAttribute("thing", s);
			return ERROR;
		}
		if(st.equals("passwordError")){
			String s="密码错误";
			request.setAttribute("thing", s);
			return ERROR;
		}
		if(st.equals("success")){
			//登录成功后，将用户名塞入到HttpSession里面
			ActionContext context=ActionContext .getContext();
			String name=user.getUsername();
			context.getSession().put("isLogin",name);
			
			//登录成功后，将用户级别放入到session里面
			String s=logindao.selectLv(user);
			context.getSession().put("lv",s);
			return SUCCESS;
		}
		return ERROR;
	}

	public Userprofile getUser() {
		return user;
	}

	public void setUser(Userprofile user) {
		this.user = user;
	}
	
	
}
